package com.example.gulimall.seckill.config;

import com.example.gulimall.seckill.service.SeckillService;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.concurrent.TimeUnit;

@EnableAsync
@EnableScheduling
@Configuration
public class ScheduledConfig {
    @Autowired
    RedissonClient redisson;
    @Autowired
    SeckillService seckillService;
    //秒杀商品上架功能的锁
    private final String upload_lock = "seckill:upload:lock";
    @Async
    @Scheduled(cron = "0 0 3 * * ?")
    public void uploadSeckillSkuLatest3Days(){
        RLock lock = redisson.getLock(upload_lock);
        lock.lock(10, TimeUnit.SECONDS);
        try{
            seckillService.uploadSeckillSkuLatest3Days();
        }
        finally {
            lock.unlock();
        }
    }
}
